#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
  QMainWindow(parent), tray(NULL)
{
  // Start local server
  srv = new LocalServer(this);
  srvThread = new QThread(this);

  connect(srvThread, SIGNAL(started()), srv, SLOT(init()));
  connect(srvThread, SIGNAL(finished()), srv, SLOT(done()));
  srv->moveToThread(srvThread);
  srvThread->start();

  icon = new QIcon(":/img/icon.png");

  if(QSystemTrayIcon::isSystemTrayAvailable() && QSystemTrayIcon::supportsMessages())
  {
      tray = new TrayIcon(this, icon);
      tray->show();
  }

  setWindowIcon(*icon);
  setWindowTitle(tr("Rift Tool App"));
  setFixedSize(480, 640);
  setWindowFlags(Qt::WindowTitleHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint | Qt::CustomizeWindowHint);

  statusBar = new StatusBar(this);
  setStatusBar(statusBar);

  tabs = new QTabWidget(this);

  simulTab = new SimulatorTab(tabs);
  evtTab = new EventTab(tabs);
  chatTab = new ChatTab(tabs);
  optTab = new OptionTab(tabs);

  tabs->setGeometry(10, 10, 460, 610);
  tabs->addTab(simulTab, QIcon(), tr("Simulator"));
  tabs->addTab(evtTab, QIcon(), tr("Event list"));
  tabs->addTab(chatTab, QIcon(), tr("Chat"));
  tabs->addTab(optTab, QIcon(), tr("Options"));

  connect(optTab, SIGNAL(eventListenToIt(Shard)), evtTab, SLOT(listenToIt(Shard)));
  connect(optTab, SIGNAL(eventStopListening()), evtTab, SLOT(stopListening()));
  connect(evtTab, SIGNAL(listening(Shard)), statusBar, SLOT(eventListenToIt(Shard)));
  connect(evtTab, SIGNAL(listening(Shard)), optTab, SLOT(eventListening(Shard)));
  connect(evtTab, SIGNAL(stopping()), statusBar, SLOT(eventStopListening()));
  connect(evtTab, SIGNAL(stopping()), optTab, SLOT(eventStopping()));
}

MainWindow::~MainWindow()
{
  srvThread->quit();
  srvThread->wait();

  delete srv;

  delete icon;
}

void MainWindow::showUp()
{
  show();
  raise();
  activateWindow();
}

void MainWindow::showSimulator()
{
  tabs->setCurrentIndex(0);
  showUp();
}

void MainWindow::showEventList()
{
  tabs->setCurrentIndex(1);
  showUp();
}

void MainWindow::showChat()
{
  tabs->setCurrentIndex(2);
  showUp();
}

void MainWindow::showOptions()
{
  tabs->setCurrentIndex(3);
  showUp();
}
